(function () {
	"use strict"
	angular
	.module('ydApp')
	.directive("infiniteList", infiniteList);

	function infiniteList ($timeout) {
		return{
		    transclude: true,
		    scope: {
		      scroll: '&',
		      infiniteScrollDistance: '='
		    },
    		template: '<div ng-transclude style="float:left;width: 100%;"></div>',
    		link: function (scope, elem) {
    			if (scope.infiniteScrollDistance === undefined) {
			    	scope.infiniteScrollDistance = 0;
			    }
			    var loading = false;
		        var container = $(elem).find(">div");
		        $(window).resize(function () {
		        	console.log("resize");
		        })
		        elem.on("scroll", function (event) {
		        	if (loading) {
		        		return;
		        	};
		        	if ($(elem).scrollTop() <= scope.infiniteScrollDistance) {
		        		loading = true;
		        		var height = $(container).height();
		        		var result = scope.scroll();
		        		(function (resortPosition) {
		        			if (result && typeof result.then === 'function') {
				              	result.then(resortPosition);
				            } else {
				              	resortPosition();
				            }
		        		})(function () {
		        			$timeout(function () {
			        			$(elem).scrollTop($(elem).scrollTop()+$(container).height() - height);
	           					loading = false;
			        		}, 0)
		        		})
		        	};
		        })
    		}
		}
	}
})();